package com.dmzapp.api.servlet;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.util.Constant;
import com.dmzapp.api.util.MD5Checksum;

public class TokenFilter implements Filter {

    Logger logger = LoggerFactory.getLogger("dmzlog");

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    public String getRemortIP(HttpServletRequest request) {

        if (request.getHeader("x-forwarded-for") == null) {

            return request.getRemoteAddr();

        }

        return request.getHeader("x-forwarded-for");

    }

    
    /**
     * SDK端操作： 目标字符串a：deviceid”|”serviceCurrentTime的MD5， 干扰字符串b：32位MD5随机数
     * 干扰字符串c：32位MD5随机数
     * 
     * 将三个串按照以下规则并到一起 a0b0c0a1b1bca2b2c2……a16b16c16 a17b17c17……
     * 通过上面得到一个32*3长度的字符串，最后将其前48和后48调换位置：
     * 
     * 最终得到： a16b16c16 a17b17c17……a0b0c0a1b1bca2b2c2……作为传个服务器的token
     * 
     * 服务器端操作
     * 服务器通过deviceid+serviceCurrentTime算出MD5的字符串a’（交换token的前后48位，提取第0、3、6、9…位字符再组成新的32位字符。），再从传过来的token中提取目标字符串a，最后比较a’跟a是否匹配。
     * 
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {

        logger.debug(request.getParameter("v_code") + "|request from ip: " + getRemortIP((HttpServletRequest) request));
        request.setCharacterEncoding("UTF-8");
        request.setAttribute("i", getRemortIP((HttpServletRequest) request));
        response.setCharacterEncoding("UTF-8");

        String serverTime = request.getParameter("servertime");
        String token = request.getParameter("token");

        boolean flg = false;
        if (Calendar.getInstance().getTimeInMillis() - Long.valueOf(serverTime) < Constant.EXPIRED_TIME) {
            String deviceid = request.getParameter("d");
//            String macAddress = request.getParameter("m");
            
            StringBuilder sb = new StringBuilder();
            sb.append(deviceid).append("|").append(serverTime);
            
            try {
                String realToken = MD5Checksum.getChecksum4String(sb.toString());
                
                StringBuilder clientRealToken = new StringBuilder();
                
                String exchangedToken = token.substring(48, 96) + token.substring(0, 48);
                if (exchangedToken != null && exchangedToken.length() == 96) {
                    char [] array = exchangedToken.toCharArray();
                    for (int i = 2; i < array.length; i = i + 3) {
                        clientRealToken.append(array[i]);
                    } 
                }

                if (realToken.equals(clientRealToken.toString())) {
                    flg = true;
                } else {
                    response.getWriter().append("Invalid request");
                }
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (flg) {
            chain.doFilter(request, response);
        } else {
            
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    
}
